package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.OrdersDTO;
import com.sky.dto.OrdersPageQueryDTO;
import com.sky.dto.OrdersPaymentDTO;
import com.sky.dto.OrdersSubmitDTO;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.OrderBusinessException;
import com.sky.mapper.*;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.webSocket.WebSocketServer;
import io.swagger.annotations.ApiOperation;
import io.swagger.util.Json;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class OrderServiceImpl implements OrderService {
    @Autowired
    private AddressBookMapper addressBookMapper;
    @Autowired
    private OrderMapper orderMapper;
    @Autowired
    private OrderDetailMapper orderDetailMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private WebSocketServer webSocketServer;


    /**
     * 用户下单功能
     *
     * @param ordersSubmitDTO
     * @return
     */

    @ApiOperation("下单功能")
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //需求分析：找字段吧
        /**
         * 1/向订单表插入一条数据
         * 2、向明细表插入多条数据
         * 3、下单成功后需要清楚购物车
         */
        Long userId = BaseContext.getCurrentId();
        //需要先判断地址是否为空，且购物车是否为空
        Long addressBookId1 = ordersSubmitDTO.getAddressBookId();
        AddressBook byId1 = addressBookMapper.getById(addressBookId1);
        if (byId1==null){
            throw new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }

        //购物车
        List<ShoppingCart> shoppingCartList = shoppingCartMapper.showGetByID(userId);
        if (shoppingCartList ==null || shoppingCartList.size()==0){
            throw new AddressBookBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        Orders orders = new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO, orders);//先把传过来的数据拷贝

        //获取到地址信息表数据，其中就有用户电话等信息

        Long addressBookId = orders.getAddressBookId();
        AddressBook byId = addressBookMapper.getById(addressBookId); //改地址信息

        orders.setAddress(byId.getDetail());//详情地址
        orders.setPhone(byId.getPhone());
        orders.setOrderTime(LocalDateTime.now());
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setPayStatus(Orders.PAID);
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setConsignee(byId.getConsignee());
        orders.setCancelTime(LocalDateTime.now());
        orders.setUserId(userId);

        //插入订单表和订单明细表
        orderMapper.addOrder(orders);
        //订单明细表
        //订单明显的数据主要是从购物车来的了
//        List<ShoppingCart> shoppingCartList = shoppingCartMapper.showGetByID(userId);
        //该用户下的所有菜品
        List<OrderDetail> list = new ArrayList<>();
        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            orderDetail.setOrderId(orders.getId());
            list.add(orderDetail);
            //建议批量插入
            //OrderDetailMapper.addOrderDetail(orderDetail);
        }
        orderDetailMapper.addDetailList(list);

        //清空购物车，根据用户id就好了
        shoppingCartMapper.clean(userId);

        //然后就是分装返回数据了
        OrderSubmitVO orderSubmitVO = OrderSubmitVO.builder()
                .id(orders.getId())
                .orderAmount(orders.getAmount())
                .orderNumber(orders.getNumber())
                .orderTime(orders.getOrderTime())
                .build();
        //记住sendToAllClient  session回话基本就包含3部分type、order、content
        Map map=new HashMap();
        map.put("type",1);
        map.put("orderId",orders.getId());
        map.put("订单号为：",orders.getNumber());
        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);
        log.info("订单提醒！！！！！{},---{}",orders.getNumber(),orders.getId());

        return orderSubmitVO;
    }


    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();
        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单
        JSONObject jsonObject = weChatPayUtil.pay(
                ordersPaymentDTO.getOrderNumber(), //商户订单号
                new BigDecimal(0.01), //支付金额，单位 元
                "苍穹外卖订单", //商品描述
                user.getOpenid() //微信用户的openid
        );

        if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {
            throw new OrderBusinessException("该订单已支付");
        }

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));

        return vo;
    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {
        // 当前登录用户id
        Long userId = BaseContext.getCurrentId();

        // 根据订单号查询当前用户的订单
        Orders ordersDB = orderMapper.getByNumberAndUserId(outTradeNo, userId);

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        orderMapper.update(orders);

        //要求的数据格式是json格式，包含有type，order和content，所以最好是先封装成一个map集合再转成json格式
        Map map=new HashMap();
        map.put("type",1);
        map.put("order",ordersDB.getId());
        map.put("content","订单号:"+outTradeNo);
        String jsonString = JSON.toJSONString(map);
        webSocketServer.sendToAllClient(jsonString);

    }

    @Override
    public PageResult pageQuery(OrdersPageQueryDTO ordersPageQueryDTO) {
        //一年一度的分页查询来了
        PageHelper.startPage(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());//自行分页查询
        Long userId = BaseContext.getCurrentId();
        ordersPageQueryDTO.setUserId(userId);

        Page<Orders> records= orderMapper.pageQuery(ordersPageQueryDTO);

        //封装到VO传给结果
        List<OrderVO> list=new ArrayList<>();
        for (Orders order : records) {
            //每个订单对应的菜品
            List<OrderDetail> orderDetailList=orderDetailMapper.getByOrderId(order.getId());
            //将订单基础信息复制过来
            OrderVO orderVO=new OrderVO();
            BeanUtils.copyProperties(order,orderVO);
            //orderDetailList赋值给orderVO
            orderVO.setOrderDetailList(orderDetailList);
            list.add(orderVO);
        }

        //遍历records，再把，最后一个

        return new PageResult(records.getTotal(),list);
    }

    @ApiOperation("催单功能")
    public void reminByid(Long id) {
        //催单功能：
        //查询该订单是否存在，如果存在，进行催单
        Orders order=orderMapper.getByOrderId(id);
        if (order==null){
            throw new OrderBusinessException(MessageConstant.ORDER_NOT_FOUND);
            //进行催单

        }
        Map map=new HashMap();
        map.put("type",1);
        map.put("order",order.getId());
        map.put("content","订单号:"+order.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
    }

    /**
     * 查看订单详情
     * @param id
     * @return
     */
    @ApiOperation("查看订单详情")
    public OrderVO geyByOrderId(Long id) {
        //两部分组成：订单表、明细表
        //1订单表：
        Orders byOrderId = orderMapper.getByOrderId(id);
        //订单明细表：
        List<OrderDetail> details = orderDetailMapper.getByOrderId(id);
        OrderVO orderVO=new OrderVO();
        BeanUtils.copyProperties(byOrderId,orderVO);
        orderVO.setOrderDetailList(details);

        Map map=new HashMap();
        map.put("type",1);
        map.put("order",id);
        map.put("content","订单号:"+byOrderId.getNumber());
        webSocketServer.sendToAllClient(JSON.toJSONString(map));
        return orderVO;
    }

    //查看订单功能


}
